//
//  MainMusicTableViewController.m
//  WXMusic
//
//  Created by 漫步人生路 on 15/8/31.
//  Copyright (c) 2015年 漫步人生路. All rights reserved.
//

#import "MainMusicTableViewController.h"
#import "MainMusicHeaderView.h"
#import "MainMusicTableViewCell.h"
#import "HotListTableViewCell.h"
#import "CoverFlowModel.h"
#import "RecommendModel.h"
#import "HotListModel.h"
@interface MainMusicTableViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong)MainMusicHeaderView *mainMusicHeader;
@property (nonatomic, strong) NSMutableArray *recommendArray;
@property (nonatomic, strong) NSMutableArray *hotListArray;
@end

@implementation MainMusicTableViewController
- (void)reloadCoverFlowAndJson
{
    //传入一个url（字符串类型）
    [LORequestManger GET:kCoverFlowUrl success:^(id response) {
        //请求完数据的一些相应动作处理
        
        //使用字典类型来接收我们的response
        NSDictionary *dic = (NSDictionary *)response;
        for (NSDictionary *pic in dic[@"pic"]) {
            CoverFlowModel *coverFlowModel =
            [CoverFlowModel shareJsonWithDictionary:pic];
            [self.imageArray addObject:coverFlowModel.randpic];
        }
        [self setUpCoverFlowView];
        //打印error
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
//轮播图数组
- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [[NSMutableArray alloc]init];
    }
    return _imageArray;
}

//设置轮播图
- (void)setUpCoverFlowView
{
    self.mainMusicHeader = [[MainMusicHeaderView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 170)imageArray:self.imageArray delegate:self action:@selector(touchImage)timer:3.5 selector:@selector(circularly)];
    self.mainMusicHeader.delegate = self;
    self.tableView.tableHeaderView = self.mainMusicHeader;
}
//初始化热门推荐数组
- (NSMutableArray *)recommendArray
{
    if (!_recommendArray) {
        _recommendArray = [[NSMutableArray alloc]init];
    }
    return _recommendArray;
}
//请求热门推荐并解析
- (void)reloadRecommend
{
    [LORequestManger GET:kHotRecomendUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *contentDic = dic[@"content"];
        for (NSDictionary *listDic in contentDic[@"list"]) {
            RecommendModel *recommendModel = [RecommendModel shareJsonWithDictionary:listDic];
            //将Model添加至数组内
            [self.recommendArray addObject:recommendModel];
        }
        //刷新表视图数据
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
//初始化热门歌单数组
- (NSMutableArray *)hotListArray
{
    if (!_hotListArray) {
        _hotListArray = [[NSMutableArray alloc]init];
    }
    return _hotListArray;
}
//热门歌单网络请求与解析
- (void)reloadHotList
{
    [LORequestManger GET:kHotListUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        for (NSDictionary *content in dic[@"content"]) {
            HotListModel *hotListModel = [HotListModel shareJsonWithDictionary:content];
            [self.hotListArray addObject:hotListModel];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //轮播图数据请求与解析
    [self reloadCoverFlowAndJson];
    //热门推荐数据请求与解析
    [self reloadRecommend];
    
    [self reloadHotList];
    //将TableView的分割线去掉
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    //创建模糊视图
    BlurImageView *blurImageView = [[BlurImageView alloc]initWithFrame:kBounds];
    //将模糊视图设置为tableView的backgroundView
    self.tableView.backgroundView = blurImageView;
    //注册TableViewCell
    [self.tableView registerClass:[MainMusicTableViewCell class] forCellReuseIdentifier:@"mainMusic"];

    //第一个参数为你想要注册的类用[]括起来
    //第二个参数为我们的重用标示符
    [self.tableView registerClass:[HotListTableViewCell class] forCellReuseIdentifier:@"hotList"];
}

//自定义section的headerView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//返回值为UIView类型，那么我们首先需要有一个View在底层以供我们在其上面添加自定义的控件
    UIView *headerView = [[UIView alloc]init];
    //创建一个label添加至我们的headerView上
    UILabel *headerTitle = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 70, 25)];
    if (section == 0) {
        headerTitle.text = @"热门推荐";
    }else
    {
        headerTitle.text = @"热门歌单";
    }
    headerTitle.textColor = [UIColor whiteColor];
    headerTitle.font = [UIFont boldSystemFontOfSize:14.0];
    [headerView addSubview:headerTitle];
    //下划线
    UIView *headerLine = [[UIView alloc]initWithFrame:CGRectMake(15, 31, kWidth - 30, 1)];
    headerLine.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:headerLine];
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

//定时器设置循环滚动
- (void)circularly
{
    [self scrollViewDidCircularly];
    //创建一个newPoint每次被赋予当前scrollview的contentOffset
    CGPoint newPoint = self.mainMusicHeader.contentOffset;
    newPoint.x += kWidth;
    [self.mainMusicHeader setContentOffset:newPoint animated:YES];
}
//封装循环滚动方法在手动滑动与定时器方法内调用
- (void)scrollViewDidCircularly
{
    if (self.mainMusicHeader.contentOffset.x == 0) {
        [self.mainMusicHeader setContentOffset:CGPointMake(self.mainMusicHeader.contentSize.width - 2 * self.mainMusicHeader.bounds.size.width, 0) animated:NO];
    }
    else if (self.mainMusicHeader.contentOffset.x == self.mainMusicHeader.contentSize.width - self.mainMusicHeader.bounds.size.width) {
        [self.mainMusicHeader setContentOffset:CGPointMake(self.mainMusicHeader.bounds.size.width, 0) animated:NO];

    }
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self scrollViewDidCircularly];
}
- (void)touchImage
{
    NSInteger index = self.mainMusicHeader.contentOffset.x / kWidth;
    //起始位置为下标1，我们第一张显示的图片前面还有一张图片，所以我们需要将该下标-1，从0开始
    index -= 1;
    //当我们的index为最后一张的时候，我们将index的值设为0，以便于我们可以根据下标进行相对的操作。（页面跳转、取数组内某一个下标的值等等）
    if (index == self.imageArray.count) {
        index = 0;
    }
    NSLog(@"%ld",index);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {
        return 1;
    }else
    {
        return self.hotListArray.count;
    }

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        MainMusicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mainMusic" forIndexPath:indexPath];
        
        RecommendModel *recommendModel = [[RecommendModel alloc]init];
        [cell setUpImageViewWithTaget:self action:@selector(imageTouch:) imageArray:self.recommendArray model:recommendModel];
        
        return cell;

    }else
    {
        HotListTableViewCell *hotListCell = [tableView dequeueReusableCellWithIdentifier:@"hotList" forIndexPath:indexPath];
        //根据行来给model赋值
        HotListModel *hotListModel = [self.hotListArray objectAtIndex:indexPath.row];
        [hotListCell setValueWithModel:hotListModel];
        return hotListCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HotListModel *hotListModel = [self.hotListArray objectAtIndex:indexPath.row];
    [self pushSongsListViewControllerWithCode:hotListModel.listid];
}
- (void)imageTouch:(id)sender
{
    //创建一个UITapGestureRecognizer的实例变量来接收我们的sender
    UITapGestureRecognizer *tapSender = (UITapGestureRecognizer *)sender;
    //通过打印sender我们可以了解到UITapGestureRecognizer里面包含了一个属性是View，该View为我们的TapImageView
    //我们可以通过tapSender.view.tag - 1000来取一个个位数用来取数组的下标为用。
    
    RecommendModel *recommendModel = [[RecommendModel alloc]init];
    recommendModel = [self.recommendArray objectAtIndex:tapSender.view.tag - 1000];
    [self pushSongsListViewControllerWithCode:recommendModel.listid];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170;
}

- (void)pushSongsListViewControllerWithCode:(NSString *)code
{
    SongsListTableViewController *songsListVC = [[SongsListTableViewController alloc]initWithStyle:UITableViewStylePlain];
    songsListVC.songsListCode = code;
    songsListVC.songsType = @"首页";
    [self.navigationController pushViewController:songsListVC animated:YES];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
